using System;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ihongma.Common;

namespace ihongma.Web.admin.order
{
    public partial class order_list : Web.UI.ManagePage
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected int status;
        protected int payment_status;
        protected int express_status;
        protected string keywords = string.Empty;
        protected int payment;
        protected string DateS;
        protected string xdDate;
        protected void Page_Load(object sender, EventArgs e)
        {
            this.status = DTRequest.GetQueryInt("status");
            this.payment_status = DTRequest.GetQueryInt("payment_status");
            this.express_status = DTRequest.GetQueryInt("express_status");
            this.keywords = DTRequest.GetQueryString("keywords");
            this.payment = DTRequest.GetQueryInt("payment");
            this.DateS = DTRequest.GetQueryString("DateS");
            this.xdDate = DTRequest.GetQueryString("xddate");
            this.pageSize = GetPageSize(10); //每页数量
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("order_list", DTEnums.ActionEnum.View.ToString()); //检查权限
                RptBind("id>0" + CombSqlTxt(this.status, this.payment_status, this.express_status, this.keywords, this.payment, this.DateS, this.xdDate), "status asc,add_time desc,id desc");
            }
        }

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            this.page = DTRequest.GetQueryInt("page", 1);
            if (this.status > 0)
            {
                this.ddlStatus.SelectedValue = this.status.ToString();
            }
            if (this.payment_status > 0)
            {
                this.ddlPaymentStatus.SelectedValue = this.payment_status.ToString();
            }
            if (this.express_status > 0)
            {
                this.ddlExpressStatus.SelectedValue = this.express_status.ToString();
            }
            if (this.payment > 0)
            {
                this.ddlpayment.SelectedValue = this.payment.ToString();
            }
            txtDate.Text = this.DateS;
            txtKeywords.Text = this.keywords;
            txtXddate.Text = this.xdDate;
            BLL.orders bll = new BLL.orders();
            this.rptList.DataSource = bll.GetList(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = Utils.CombUrlTxt("order_list.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&DateS={4}&payment={5}&page={6}&xddate={7}",
                this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords,this.DateS,this.payment.ToString(),"__id__",this.xdDate);
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(int _status, int _payment_status, int _express_status, string _keywords, int payment,string DateS,string xdDate)
        {
            StringBuilder strTemp = new StringBuilder();
            if (_status > 0)
            {
                strTemp.Append(" and status=" + _status);
            }
            if (_payment_status > 0)
            {
                strTemp.Append(" and payment_status=" + _payment_status);
            }
            if (_express_status > 0)
            {
                strTemp.Append(" and express_status=" + _express_status);
            }
            if (payment > 0)
            {
                strTemp.Append(" and payment_id=" + payment);
            }
            DateS = DateS.Replace("'", "");
            if (!string.IsNullOrEmpty(DateS))
            {
                strTemp.Append(" and id in (SELECT [order_id] FROM [dt_order_goods] where deliverytime='" + DateS + "')");
            }
            if (!string.IsNullOrEmpty(xdDate))
            {
                strTemp.Append(" and datediff(day,'"+xdDate+"',[add_time])=0");
            }
            _keywords = _keywords.Replace("'", "").Trim();
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and (order_no like '%" + _keywords + "%' or user_name like '%" + _keywords + "%' or accept_name like '%" + _keywords + "%' or user_id in (SELECT [id] FROM [dt_users] where [mobile] like '%" + _keywords + "%'))");
            }
            return strTemp.ToString();
        }
        #endregion

        #region 返回用户每页数量=========================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("order_list_page_size"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        #region 返回订单状态=============================
        protected string GetOrderStatus(int _id)
        {
            string _title = string.Empty;
            Model.orders model = new BLL.orders().GetModel(_id);
            switch (model.status)
            {
                case 1: //如果是线下支付，支付状态为0，如果是线上支付，支付成功后会自动改变订单状态为已确认
                    if (model.payment_status > 0)
                    {
                        _title = "待付款";
                    }
                    else
                    {
                        _title = "待确认";
                    }
                    break;
                case 2: //如果订单为已确认状态，则进入发货状态
                    if (model.express_status > 1)
                    {
                        _title = "已发货";
                    }
                    else
                    {
                        _title = "待发货";
                    }
                    break;
                case 3:
                    _title = "交易完成";
                    break;
                case 4:
                    _title = "已取消";
                    break;
                case 5:
                    _title = "已作废";
                    break;
            }

            return _title;
        }
        #endregion

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("order_list.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&DateS={4}&payment={5}&xddate={6}",
          this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), txtKeywords.Text, this.DateS, this.payment.ToString(),this.xdDate));
        }

        //订单状态
        protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("order_list.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&DateS={4}&payment={5}&xddate={6}",
           ddlStatus.SelectedValue, this.payment_status.ToString(), this.express_status.ToString(), this.keywords, this.DateS, this.payment.ToString(),this.xdDate));
        }

        //支付状态
        protected void ddlPaymentStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("order_list.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&DateS={4}&payment={5}&xddate={6}",
        this.status.ToString(), ddlPaymentStatus.SelectedValue, this.express_status.ToString(), this.keywords, this.DateS, this.payment.ToString(),this.xdDate));
        }

        //发货状态
        protected void ddlExpressStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("order_list.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&DateS={4}&payment={5}&xddate={6}",
         this.status.ToString(), this.payment_status.ToString(), ddlExpressStatus.SelectedValue, this.keywords, this.DateS, this.payment.ToString(),this.xdDate));
        }

        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("order_list_page_size", _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(Utils.CombUrlTxt("user_list.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}}&DateS={4}&payment={5}&xddate={6}",
                this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords, this.DateS, this.ddlpayment.SelectedValue,this.xdDate));
        }

        //批量删除
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("order_list", DTEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            BLL.orders bll = new BLL.orders();
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (bll.Delete(id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除订单成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("order_list.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&DateS={4}&payment={5}&xddate={6}",
                this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords, this.DateS, this.ddlpayment.SelectedValue, this.xdDate), "Success");
        }

        protected void ddlpayment_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("order_list.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&DateS={4}&payment={5}&xddate={6}",
         this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords, this.DateS, this.ddlpayment.SelectedValue,this.xdDate));

        }

        protected void rptList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {


            //判断里层repeater处于外层repeater的哪个位置（ AlternatingItemTemplate，FooterTemplate，

            //HeaderTemplate，，ItemTemplate，SeparatorTemplate）
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater rep = e.Item.FindControl("rpquestionlist") as Repeater;//找到里层的repeater对象
                DataRowView rowv = (DataRowView)e.Item.DataItem;//找到分类Repeater关联的数据项 
                int typeid = Convert.ToInt32(rowv["id"]); //获取填充子类的id 
                var tempdate =txtDate.Text.Replace("'", "");
                if (!string.IsNullOrEmpty(tempdate))
                {
                    rep.DataSource = new BLL.order_goods().GetList("deliverytime='" + tempdate + "' and order_id=" + typeid);
                    //strTemp.Append(" and id in (SELECT [order_id] FROM [dt_order_goods] where deliverytime='" + DateS + "')");
                }
                else
                {
                    rep.DataSource = new BLL.order_goods().GetList("order_id=" + typeid);
                }
                rep.DataBind();

            }
        }

        protected void lbtnDateSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("order_list.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&DateS={4}&payment={5}&xddate={6}",
            this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords, txtDate.Text, this.payment.ToString(),this.xdDate));
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            string ExcelName = "PlayerFundOutListing_" + DateTime.Now.ToString("yyyyMMdd") + ".xls";
            CreateExcelFromTable(ChangeParantIDToParentExcel().Tables[0], ExcelName);
            //new BLL.orders().GetList(
            //InsusExportToExcel obj = new InsusExportToExcel();
            //obj.ExportToExcel(rptList, "catalog");
           // ExportData.ExportControl(rptList, "Excel");
        }

        private void CreateExcelFromTable(DataTable table, string FileName)
        {
            HttpResponse response = Page.Response;
            response.ContentEncoding = System.Text.Encoding.GetEncoding("GBK");
            response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
            int index = 0;
            string headers = "";
            for (index = 0; index < table.Columns.Count; index++)
            {
                headers += table.Columns[index].ColumnName + "\t";
            }
            headers += "\n";
            response.Write(headers);
            response.Flush();

            foreach (DataRow row in table.Rows)
            {
                string rowContent = "";
                foreach (DataColumn column in table.Columns)
                {
                    rowContent += row[column.ColumnName].ToString() + "\t";
                }
                rowContent += "\n";
                response.Write(rowContent);
                response.Flush();
            }
            response.End();
        }

        private DataSet ChangeParantIDToParentExcel()
        {
            DataSet ds = new DataSet();
            DataTable tmpDt = new DataTable();

            tmpDt.Columns.Add("订单号");
            tmpDt.Columns.Add("会员账号");
            tmpDt.Columns.Add("订购来源");
            tmpDt.Columns.Add("支付方式");
            tmpDt.Columns.Add("订单状态");
            tmpDt.Columns.Add("总金额");
            tmpDt.Columns.Add("商品名称");
            tmpDt.Columns.Add("商品数量");
            tmpDt.Columns.Add("下单日期");
            tmpDt.Columns.Add("发货日期");
                              tmpDt.Columns.Add("收货时间");
              tmpDt.Columns.Add("冷藏包");
             
            tmpDt.Columns.Add("发货人姓名");
            tmpDt.Columns.Add("发货地址");
            tmpDt.Columns.Add("发货人电话");

            DataRow dr;

            BLL.orders bll = new BLL.orders();
            string _strWhere = "id>0" + CombSqlTxt(this.status, this.payment_status, this.express_status, this.keywords, this.payment, this.DateS,this.xdDate);
            string _orderby = "status asc,add_time desc,id desc";
            var ListData = bll.GetList(0, _strWhere, _orderby).Tables[0].Rows;


            foreach (DataRow item in ListData)
            {
             
                string where = "order_id=" + item["id"].ToString();
                var tempdate = txtDate.Text.Replace("'", "");
                if (!string.IsNullOrEmpty(tempdate))
                {
                    where = where + " and deliverytime='" + tempdate+"'";
                }

                foreach (var i in new BLL.order_goods().GetModelList(where))
                {
                    dr = tmpDt.NewRow();

                    dr["订单号"] = item["order_no"].ToString();
                    dr["会员账号"] = item["user_name"].ToString();
                    dr["订购来源"] = item["address"].ToString() == "" ? "网站订购" : item["address"].ToString();
                    dr["支付方式"] = new ihongma.BLL.payment().GetTitle(Convert.ToInt32(item["payment_id"]));

                    dr["订单状态"] = GetOrderStatus(Convert.ToInt32(item["id"].ToString()));
                    dr["总金额"] = item["order_amount"].ToString();
                    dr["商品名称"] = i.goods_title;
                    dr["商品数量"] = i.quantity;
                    dr["下单日期"] = item["add_time"].ToString();
                    dr["发货日期"] = i.deliverytime.ToString("yyyy-MM-dd");
                    dr["收货时间"] = i.field1 == "1" ? "2:00pm-6:00pm" : "6:00pm-10:00pm";
                    dr["冷藏包"] = item["area"].ToString();
                    var addressm = new BLL.user_address().GetModel(i.address_id);
                    if (addressm != null)
                    {
                        dr["发货人姓名"] = addressm.name;
                        dr["发货地址"] =addressm.area+addressm.address;
                        
                        dr["发货人电话"] = addressm.mobile;
                    }
                    tmpDt.Rows.Add(dr);
                }
            }

            tmpDt.AcceptChanges();
            ds.Tables.Add(tmpDt);

            return ds;
        }

        protected void lbtnXdDateSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("order_list.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&DateS={4}&payment={5}&xddate={6}",
           this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords, this.DateS, this.payment.ToString(),this.txtXddate.Text));
        }

    }
}